<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="40">
        <el-col :span="9">
          <el-input
            placeholder="请输入需要查询的用户信息..."
            clearable
            v-model="queryTxt"
            @clear="getUserList"
            @keyup.13="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-button type="primary" @click="addDialogVisible = true"
          >添加</el-button
        >
        <el-col :span="4"> </el-col>
      </el-row>
      <!-- 用户表格展示区域 -->
      <el-row>
        <el-table :data="userlist" stripe border>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
              >
                <!-- active-color="#13ce66"
                inactive-color="#ff4949" -->
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改用户"
                :enterable="false"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除用户"
                :enterable="false"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteUser(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button type="warning" icon="el-icon-setting"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
         <el-pagination
      @size-change="handleSizeChange"
      @current-change="headleCurrentChange"
      @prev-click="headlePrev"
      @next-click="headleNext"
      :current-page="page"
      :page-sizes="[3,6,9,12,15,20,30,40,50,100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
      </el-row>
    </el-card>

    <!-- 添加用户模式窗口 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 正文区域 -->
      <el-form
        :rules="addFormRules"
        ref="addFormRef"
        :model="user"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="user.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户模式窗口 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 正文区域 -->
      <el-form
        :rules="addFormRules"
        ref="addFormRef"
        :model="editUser"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editUser.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      let reg = /^\w+@[A-Za-z\d]{2,3}\.[a-zA-Z]{2,3}([a-zA-Z]{2,3})?$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的邮箱.."));
      }
    };
    return {
      queryTxt: "",
      userlist: [],
      page: 1, //当前页数
      limit: 3, //每页显示的条数
      totalCount: 0, //查询的总数
      addDialogVisible: false, //控制添加窗口的显示和隐藏
      editDialogVisible: false, //控制修改窗口的显示和隐藏
      user: {}, //存储用户对象
      editUser: {},
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度6 到 15 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 调用自定义验证规则
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { min: 5, max: 11, message: "长度5 到 11 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //实例被创建的时候就会被执行
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    getUserList() {
      let url = `users?_page=${this.page}&_limit=${this.limit}`;
      // 如果搜索框中有值
      if (this.queryTxt) {
        url = `users?_page=${this.page}&_limit=${this.limit}&q=${this.queryTxt}`;
      }
      this.$http.get(url).then((res) => {
        this.userlist = res.data;
        //获取数据的总行数
        console.log(res)
        console.log(res.headers['x-total-count'])
        this.totalCount = parseInt(res.headers["x-total-count"]);
      });
    },
    // 修改用户状态
    userStateChanged(row) {
      console.log(row);
      //  users/
      this.$http.put("/users/" + row.id, row).then((rs) => {
        if (rs.status !== 200) {
          return this.$message.error("修改用户状态失败!");
        }
        this.$message.success("更新用户状态成功!");
      });
    },
    //监听用户添加关闭事件方法,重置表单
    addDialogClosed() {
      //使用引用表单名称重置表单
      this.$refs.addFormRef.resetFields();
    },
    //监听用户修改关闭事件方法,重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 添加用户
    add() {
      //判断验证规则
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return false;
        this.$http.post("users", this.user).then((res) => {
          if (res.status !== 201) {
            this.$message.error("用户添加失败...");
          } else {
            this.$message.success("用户添加成功...");
          }
          this.addDialogVisible = false;
          this.getUserList();
        });
      });
    },
    //显示修改用户
    showEditDialog(row) {
      console.log(row);
      this.editUser = row;
      this.editDialogVisible = true;
    },
    //修改用户
    editUserInfo() {
      //判断验证规则
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.$http
            .put("users/" + this.editUser.id, this.editUser)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success("用户信息修改成功...");
              } else {
                this.$message.error("用户信息修改失败...");
              }
              this.getUserList();
              this.editDialogVisible = false;
            });
        }
      });
    },

    // //删除用户
    deleteUser(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("users/" + row.id).then((res) => {
            if (res.status !== 200) {
              return this.$message.error("删除失败!");
            }
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          }); 
        });
    },

    //当改变每页显示的条数的时候执行
    handleSizeChange(size) {
      this.$message("改变每页显示的数量");
      this.limit = size;
      this.getUserList();
    },
    //当单击页数的时候执行
    headleCurrentChange(page) {
      this.page= page;
      this.getUserList();

      this.$message("单击的页数");
    },
    headlePrev(page) {
      this.page= page;
      this.getUserList();

      this.$message("单击的上一页");
    },
    headleNext(page) {
      this.page= page;
      this.getUserList();

      this.$message("单击的下一页");
    },
  },
};
</script>
<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
.el-table {
  .el-button {
    padding: 10px;
  }
}
</style>